/**
 * @file 0502_shared_ptr.cpp
 * @author Kun (kun_g@msn.com)
 * @brief shared_ptr 示例
 * @version 0.1
 * @date 2024-06-10
 *
 * @copyright Copyright (c) 2024
 *
 */
#include <iostream>
#include <memory>
#include <string>
#include <vector>

using namespace std;

/**
 * @brief  打印 vector<shared_ptr<string>> 列表
 *
 * @param  who    vector<shared_ptr<string>> 类型
 */
void print_ptr(vector<shared_ptr<string>> who);

int main() {
  {
    //! 创建 shared_ptr
    shared_ptr<string> p1(new string("hello"));
    shared_ptr<string> p2{new string("hello")};
    shared_ptr<string> p3 = make_shared<string>("world"); // 不能直接=赋值
    shared_ptr<string> p4;
    p4.reset(new string("world")); //! 如果是先声明再赋值，需要用 reset() 方法
  }
  shared_ptr<string> p_nico(new string("nico"));
  shared_ptr<string> p_jutta(new string("jutta"));

  (*p_nico)[0] = 'N';
  p_jutta->replace(0, 1, "J");

  vector<shared_ptr<string>> who_made_coffee;
  who_made_coffee.push_back(p_jutta);
  who_made_coffee.push_back(p_jutta);
  who_made_coffee.push_back(p_nico);
  who_made_coffee.push_back(p_jutta);
  who_made_coffee.push_back(p_nico);

  print_ptr(who_made_coffee);

  *p_nico = "Nicolas";

  print_ptr(who_made_coffee);

  cout << "p_nico.use_count() = " << who_made_coffee[0].use_count() << endl;

  return 0;
}

void print_ptr(vector<shared_ptr<string>> who) {
  for (auto ptr : who) {
    cout << *ptr << " ";
  }
  cout << endl;
}